package com.bert.controller;

import com.bert.entity.PerformanceEntity;
import com.bert.service.CallService;
import com.bert.service.TestService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;

@RequestMapping("/test")
@RestController
public class TestController {

    @DubboReference(timeout = 1200)
    private TestService testService;
    @DubboReference(timeout = 1200)
    private CallService callService;

    @GetMapping("/test")
    public String test() {
        return "OK";
    }

    @GetMapping("/one")
    public String getOneService(String name) {
        return testService.getTest(name);
    }

    @GetMapping("/call")
    public String callTest(String name) {
        return callService.callTest(name);
//        return "";
    }

    @RequestMapping("/number")
    public PerformanceEntity printMessage(@RequestParam long number) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < number; i++) {
            testService.getTest("test");
        }
        long endTime = System.currentTimeMillis();
        return this.getTime("dubbo", number, startTime, endTime);
    }

    private PerformanceEntity getTime(String name, long number, long startTime, long endTime){
        long totalTime = endTime - startTime;
        BigDecimal averageTime = this.getNumber(3, totalTime, number);
        BigDecimal tps = this.getNumber(0, number * 1000, totalTime);
        return PerformanceEntity.builder()
                .project(name + "循环调用 "+ number +"次")
                .totalTime(totalTime + " ms")
                .averageTime(averageTime + " ms")
                .TPS(tps + " r/s")
                .build();
    }

    private BigDecimal getNumber(int n, long a, long b){
        if (b == 0L) {
            b = 1L;
        }
        return BigDecimal.valueOf(a).divide(BigDecimal.valueOf(b), n, RoundingMode.HALF_UP);
    }

}
